<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @open="dialogOpen" @close="closeRoleDialog">
    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="closeRoleDialog">取消</el-button>
    </template>
  </el-dialog>

</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      roleIds: [],
      list: []
    }
  },
  // created() {
  //   this.getRoleList()
  // },
  methods: {
    closeRoleDialog() {
      this.$emit('update:showRoleDialog', false)
      this.roleIds = []
      this.list = []
    },
    async getRoleList() {
      const { data } = await reqGetRoleList(1, 100)
      this.list = data.rows
      return data.rows
    },
    dialogOpen() {
      this.loading = true
      // this.getRoleList()
      // this.getUserDetailById()
      // Promise.all
      // Promise.all([]) - 参数是个数组
      // Promise.all([promise1, promise2, ....]) 标准用法，数组里的每一项promise
      // Promise.all返回值 也是Promise
      // 因为返回值是Promise实例 所以也可以.then
      // then里面的参数结果，是多个promise成功结果拼成数组[res1, res2....]
      Promise.all([this.getRoleList(), this.getUserDetailById()]).then(() => {
        this.loading = false
      })
    },
    async getUserDetailById() {
      const { data } = await reqGetUserDetailById(this.userId)
      this.roleIds = data.roleIds
      return data.roleIds
    },
    async clickSubmit() {
      await reqAssignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.closeRoleDialog()
    }
  }
}
</script>

<style>

</style>
